#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define BUF_SIZE 30
void error_handling(char *message);

int main(void){
    int serv_sd =-1;
    int tongxun_sd=-1;

    FILE *fp;
    char buf[BUF_SIZE];
    int read_cnt;

    struct sockaddr_in serv_adr;
    struct sockaddr_in clnt_adr;
    socklen_t clnt_adr_sz;

    fp = fopen("file_server.txt","rb");
    if(fp==NULL) 
        error_handling("fopen() error\n");

    serv_sd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(serv_sd == -1) error_handling("socket() error\n");

    memset(&serv_adr,0,sizeof(serv_adr));
    serv_adr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_adr.sin_family = AF_INET;
    serv_adr.sin_port = htons(9190);

    if(bind(serv_sd,(struct sockaddr *)&serv_adr  ,sizeof(serv_adr))==-1) 
    error_handling("bind() error\n");

    if(listen(serv_sd,5)==-1) error_handling("listen() error");
    tongxun_sd = accept (serv_sd,(struct sockaddr*)&clnt_adr,&clnt_adr_sz);
    if(tongxun_sd ==-1) error_handling("accept() error\n");

     while (1)
     {
         read_cnt = fread((void*)buf,1,BUF_SIZE,fp);
         if(read_cnt<BUF_SIZE) {
             write(tongxun_sd,(void*)buf,read_cnt);
             break;
         }
         write(tongxun_sd,buf,BUF_SIZE);
     }

     shutdown(tongxun_sd,SHUT_WR);
     read(tongxun_sd,buf,BUF_SIZE);
     printf("Message from client:%s\n",buf);

    close(tongxun_sd);
    close(serv_sd);
     fclose(fp);
    
    return 0;
}

void error_handling(char *message){
    printf(message);
    exit(0);
}
